//
//  ANMineController.m
//  WeiYiMei
//
//  Created by 李叶夫 on 2019/4/10.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANMineController.h"
#import "MineHeaderView.h"
#import "ANMineInfoController.h"
#import "ANVIPCartInfoController.h"
#import "ANMineOrderController.h"
#import "ANMineShoppingCartController.h"
#import "ANMineTicketController.h"
#import "ANAddressManagerController.h"
#import "UserInfoEntity.h"
#import "ANMineAppointmentListController.h"
#import "MineInfoFooterView.h"
#import "ANInformationController.h"
#import "ShareManager.h"
#import "ANHTMLController.h"
#import "ANFeedbackController.h"
#import "UIView+Kit.h"
#import "AppDelegate.h"
#import "UIView+Badge.h"
#import <CTAssetsPickerController.h>
#import "ANIMController.h"

@interface ANMineController ()<UITableViewDataSource,UITableViewDelegate,CTAssetsPickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UIButton *messageBtn;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) MineHeaderView *headerView;
@property (nonatomic, strong) MineInfoFooterView *footer;

@property (nonatomic, strong) UserInfoEntity *userInfoEntity;

@property (nonatomic) BOOL showUnreadRedDot;

@end

@implementation ANMineController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"个人中心";
    // 极光自定义消息
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = YES;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
    if (UserUtils.shared.isLogin) {
        [self requestUserInfo];
        [self requestUnReadMessageCount];
    }
    [self setupTitle];
}

- (void)networkDidReceiveMessage:(NSNotification *)notification
{
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    
    NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *message = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    
    if ([message.allKeys containsObject:@"pushType"] && [message[@"pushType"] intValue] == 1 && [message[@"messageSource"] intValue] == 2) {
        NSLog(@"收到新的未读消息消息：%@",content);
        self.showUnreadRedDot = YES;
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = NO;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];
}

- (void)requestUserInfo
{
    NSDictionary *body = @{@"id":UserUtils.shared.vipId};
    [URLManager.shareManager getUrlStr:Api_User_Vip_Info parameters:body entityClass:[UserInfoEntity class] success:^(NSURLResponse * _Nonnull response, BaseEntity * _Nullable baseEntity, NSDictionary * _Nullable otherResponse) {
        
        if (baseEntity) {
            if (baseEntity.code.intValue == 200) {
                self.userInfoEntity = baseEntity.data;
                self.headerView.userInfoEntity = self.userInfoEntity;
                [UserUtils.shared updateUserData:self.userInfoEntity];
                [self.tableView reloadData];
            }
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        
    }];
}

- (void)requestUnReadMessageCount
{
    NSDictionary *body = @{
                           @"messageSource":@"2"
                           };
    [URLManager.shareManager getUrlStr:Api_Get_Unread_Message_Count parameters:body success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                if ([responseObj[@"data"] intValue] > 0) {
                    self.showUnreadRedDot = YES;
                }
                else {
                    self.showUnreadRedDot = NO;
                }
                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
            }
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        
    }];
}

- (void)setupSubViews
{
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    self.headerView = [[MineHeaderView alloc] initWithFrame:CGRectMake(0, 0, 0, 2000)];
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.contentInset = UIEdgeInsetsMake(130-2000, 0, 0, 0);
    self.headerView.name = UserUtils.shared.nameString;
    self.headerView.tel = UserUtils.shared.telString;
    
    WeakSelf
    // 跳转到个人信息
    self.headerView.mineInfoHandler = ^{
        ANMineInfoController *vc = [[ANMineInfoController alloc] init];
        vc.userInfoEntity=  weakSelf.userInfoEntity;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    // 修改头像
    self.headerView.mineAvatarHandler = ^{
        [weakSelf addPhoto];
    };
    // 会员卡信息
    self.headerView.mineCartHandler = ^{
        if (weakSelf.userInfoEntity) {
            ANVIPCartInfoController *vc = [[ANVIPCartInfoController alloc] init];
            vc.userInfoEntity = weakSelf.userInfoEntity;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
    self.footer = [[MineInfoFooterView alloc] initWithFrame:CGRectMake(0, 0, 0, 90)];
    self.footer.title = @"退出登录";
    self.tableView.tableFooterView = self.footer;
    
    // 退出登录
    self.footer.sureHandler = ^{
        [weakSelf loginOut];
    };
}

- (void)addPhoto
{
    LLAlertViewController *vc = [[LLAlertViewController alloc] init];
    vc.actions = @[@"拍摄",@"从手机相册中选择"];
    vc.actionBlock = ^(NSInteger index, NSString *actionTitle) {
        if (index == 1) {
            [self takeAlbum];
        }else if (index == 0) {
            [self takePhoto];
        }
    };
    [vc presentBottomViewControllerFromController:self];
}

// 打开相册
- (void)takeAlbum
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
        
        picker.showsSelectionIndex = YES;
        
        picker.delegate = self;
        
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            picker.modalPresentationStyle = UIModalPresentationFormSheet;
        }
        
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        [window.rootViewController presentViewController:picker animated:YES completion:nil];
    });
}

// 打开相机
- (void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable:sourceType]) {
        
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = false;
        picker.sourceType = sourceType;
        picker.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        NSLog(@"请在真机中使用");
    }
}

- (void)loginOut
{
    [ANAlertManager alertMessage:@"是否退出登录？" leftTitle:@"取消" leftHandler:^(UIAlertAction * _Nonnull action) {
        
    } rightTitle:@"退出登录" rightHandler:^(UIAlertAction * _Nonnull action) {
        [UserUtils.shared clearData];
        [[UIViewController currentTabBarController] setSelectedIndex:0];
        [UserUtils showLoginVc];
        AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [delegate removeJPCustomNotification];
    }];
    
}

- (void)shareAction
{
    // 截图
    UIImage *img = [self.tableView screenshots];
    UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
    imgView.frame = CGRectMake(30, 30, kScreenW-60, kScreenH-60);
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:imgView];
}

// 上传头像
- (void)uploadAvatar:(UIImage *)avatar
{
    [URLManager.shareManager uploadUrlStr:Api_Upload_Avatar images:@[avatar] parameters:nil fileDataName:@"upFile" success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObj) {
        
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                [self requestUserInfo];
            }
            else {
                [MBProgressHUD showError:responseObj[@"message"]];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}


#pragma mark - CTAssetsPickerControllerDelegate
//从相册选取图片后会调用该代理
-(BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
    if (asset.mediaType != PHAssetMediaTypeImage)
    {
        [MBProgressHUD showMessage:@"只能上传照片"];
        return NO;
    }
    if (picker.selectedAssets.count == 1) {
        [MBProgressHUD showError:@"只能选择一张照片"];
        return NO;
    }
    return YES;
}

// 在相册中选择图片后调用此代理
- (void)assetsPickerController:(CTAssetsPickerController *)picker didSelectAsset:(PHAsset *)asset
{
    
}

// 在相册中取消选择图片后调用此代理
- (void)assetsPickerController:(CTAssetsPickerController *)picker didDeselectAsset:(PHAsset *)asset
{
    
}

- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets {
    //关闭相册界面
    [picker dismissViewControllerAnimated:YES completion:^{
        
        
        PHAsset *asset = assets.firstObject;
        CGFloat scale = [UIScreen mainScreen].scale;
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.synchronous = YES;
        options.resizeMode = PHImageRequestOptionsResizeModeNone;
        CGSize size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
    
        [[PHImageManager defaultManager] requestImageForAsset:asset
                                                   targetSize:size
                                                  contentMode:PHImageContentModeDefault
                                                      options:options
                                                resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                    UIImage *img = result;
                                                    NSData *bigData = UIImagePNGRepresentation(result);
                                                    if (bigData.length > 400 * 1024) {
                                                        NSData *data = UIImageJPEGRepresentation(result, 400*1024.0/bigData.length);
                                                        img = [UIImage imageWithData:data];
                                                    }
                                                    
                                                    dispatch_async(dispatch_get_main_queue(), ^{
                                                        [self uploadAvatar:img];
                                                    });
                                                }];

    }];
    
}

#pragma mark - UINavigationControllerDelegate,UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //关闭相机界面
    UIImage *img = nil;
    if ([picker allowsEditing]) {
        img = [info objectForKey:UIImagePickerControllerEditedImage];
    }
    else {
        img = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    NSData *bigData = UIImagePNGRepresentation(img);
    if (bigData.length > 400 * 1024) {
        NSData *data = UIImageJPEGRepresentation(img, 400*1024.0/bigData.length);
        img = [UIImage imageWithData:data];
    }
    [self uploadAvatar:img];
    [picker dismissViewControllerAnimated:false completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 6;
    }
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"minecell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"minecell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.textColor = kColor333333;
        cell.detailTextLabel.textColor = kColor777777;
        cell.detailTextLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
    }
    cell.textLabel.showDot = @0;
    cell.textLabel.badgeOriginX = @65;
    cell.textLabel.badgeOriginY = @4;
    cell.detailTextLabel.text = @"";
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"我的订单";
            cell.imageView.image = [UIImage imageNamed:@"p_dingdan"];
        }
        if (indexPath.row == 1) {
            cell.textLabel.text = @"我的购物车";
            cell.imageView.image = [UIImage imageNamed:@"p_shopping"];
        }
        if (indexPath.row == 2) {
            cell.textLabel.text = @"我的优惠券";
            cell.imageView.image = [UIImage imageNamed:@"p_card"];
            if (self.userInfoEntity.couponNum != nil && self.userInfoEntity.couponNum.intValue > 0) {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@张",self.userInfoEntity.couponNum];
            }
            
        }
        if (indexPath.row == 3) {
            cell.textLabel.text = @"我的预约";
            cell.imageView.image = [UIImage imageNamed:@"p_yuyue"];
        }
        if (indexPath.row == 4) {
            cell.textLabel.text = @"资讯";
            cell.imageView.image = [UIImage imageNamed:@"p_news"];
        }
        if (indexPath.row == 5) {
            cell.textLabel.text = @"地址管理";
            cell.imageView.image = [UIImage imageNamed:@"p_address"];
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"意见反馈";
            cell.imageView.image = [UIImage imageNamed:@"p_advise"];
        }
        if (indexPath.row == 1) {
            cell.textLabel.text = @"关于我们";
            cell.imageView.image = [UIImage imageNamed:@"p_us"];
        }
        if (indexPath.row == 2) {
            cell.textLabel.text = @"APP分享";
            cell.imageView.image = [UIImage imageNamed:@"mine_share"];
        }
        if (indexPath.row == 3) {
            cell.textLabel.text = @"联系客服";
            cell.imageView.image = [UIImage imageNamed:@"kefu"];
            cell.textLabel.showDot = @(self.showUnreadRedDot);
        }
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            ANMineOrderController *vc = [[ANMineOrderController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        if (indexPath.row == 1) {
            ANMineShoppingCartController *vc = [[ANMineShoppingCartController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        if (indexPath.row == 2) {
            ANMineTicketController *vc = [[ANMineTicketController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        if (indexPath.row == 3) {
            ANMineAppointmentListController *vc = [[ANMineAppointmentListController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        if (indexPath.row == 4) {
            ANInformationController *vc = [[ANInformationController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        if (indexPath.row == 5) {
            ANAddressManagerController *vc = [[ANAddressManagerController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            ANFeedbackController *vc = [[ANFeedbackController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        if (indexPath.row == 1) {
            ANHTMLController *vc = [[ANHTMLController alloc] initWithUrlString:@"http://www.gdweiyimei.cn" titleName:@"关于我们"];
            [self.navigationController pushViewController:vc animated:YES];
        }
        if (indexPath.row == 2) {
            [ShareManager mq_share:@[@"唯艺美",[UIImage imageNamed:@"logo"],[NSURL URLWithString:@"http://47.112.211.215/appWym/index.html"]] target:self success:^(BOOL completed, NSString * _Nonnull message) {

            }];
            [self shareAction];
        }
        if (indexPath.row == 3) {
            ANIMController *vc = [[ANIMController alloc] init];
            vc.orgId = kKefuId;
            vc.title = @"客服";
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self setupTitle];
}

- (void)setupTitle
{
    if (self.tableView.contentOffset.y < 1830) {
        //        self.title = @"个人中心";
        //        self.navigationController.title = @"个人中心";
        [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
    }
    else {
        //        self.title = @"";
        //        self.navigationController.title = @"";
        [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]}];
    }
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
